﻿using Abp.Web.Mvc.Controllers;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web.Mvc;
using System.Xml.Linq;
using Pay.WxPay;
using Pay.AliPay;
using SingleUserMall.Orders;
using System.IO;
using System.Text;

namespace SingleUserMall.Web.Controllers
{
    public class PayController : AbpController
    {
        public OrderManager OrderManager { get; set; }
        // GET: Pay
        public ActionResult Index()
        {
            return View();
        }


        public static void Writelog(string msg)
        {
            StreamWriter stream;
            //写入日志内容
            string path = AppDomain.CurrentDomain.BaseDirectory;
            //检查上传的物理路径是否存在，不存在则创建
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            stream = new StreamWriter(path + "\\log.txt", true, Encoding.Default);
            stream.Write(DateTime.Now.ToString() + ":" + msg);
            stream.Write("\r\n");
            stream.Flush();
            stream.Close();
        }

        /// <summary>
        /// 支付宝回调
        /// </summary>
        /// <returns></returns>
        public ActionResult AliNotify()
        {
            try
            {
                //获取支付宝POST过来通知消息，并以“参数名 = 参数值”的形式组成数组
                SortedDictionary<string, string> sPara = new SortedDictionary<string, string>();
                NameValueCollection coll = HttpContext.Request.Form;
                // Get names of all forms into a string array.
                string[] requestItem = coll.AllKeys;

                for (int i = 0; i < requestItem.Length; i++)
                {
                    sPara.Add(requestItem[i], coll[requestItem[i]]);
                }
                if (sPara.Count > 0)//判断是否有带返回参数
                {
                    bool verifyResult = AliPayContext.Instance.Verify(sPara);

                    if (verifyResult)//验证成功
                    {
                        /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                        //请在这里加上商户的业务逻辑程序代码


                        //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
                        //获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表

                        //商户订单号                
                        string out_trade_no = sPara["out_trade_no"];
                        //支付宝交易号                
                        string trade_no = sPara["trade_no"];
                        //商户业务号
                        //string out_biz_no = sPara["out_biz_no"];
                        string app_id = sPara["app_id"];
                        //交易金额
                        string total_amount = sPara["total_amount"];
                        //收银账户
                        string seller_id = sPara["seller_id"];
                        //string msg = sPara["msg"];
                        //string charset = sPara["charset"];
                        //string timestamp = sPara["timestamp"];
                        //string code = sPara["code"];
                        if (sPara["trade_status"] == "TRADE_FINISHED")
                        {
                            //判断该笔订单是否在商户网站中已经做过处理
                            //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                            //如果有做过处理，不执行商户的业务程序

                            //注意：
                            //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                            //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                        }
                        else if (sPara["trade_status"] == "TRADE_SUCCESS")
                        {
                            //判断该笔订单是否在商户网站中已经做过处理
                            //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                            //如果有做过处理，不执行商户的业务程序
                            try
                            {
                                OrderManager.PayComplete(out_trade_no, decimal.Parse(total_amount),PayType.AliPay);
                                return Content("success");
                            }
                            catch
                            {
                                return Content("failure");
                            }
                            //注意：
                            //付款完成后，支付宝系统发送该交易状态通知
                            //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                        }
                        else
                        {
                        }

                        //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

                        return Content("failure");  //请不要修改或删除

                        /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                    }
                    else//验证失败
                    {
                        return Content("failure");
                    }
                }
                else
                {
                    return Content("无通知参数");
                }
            }
            catch
            {
                return Content("fail");
            }
        }

        /// <summary>
        /// 微信APP回调
        /// </summary>
        /// <returns></returns>
        public ActionResult WxAppNotify()
        {
            try
            {
                int intLen = Convert.ToInt32(HttpContext.Request.InputStream.Length);
                byte[] b = new byte[intLen];
                HttpContext.Request.InputStream.Read(b, 0, intLen);
                var postStr = System.Text.Encoding.UTF8.GetString(b);
                var res = XDocument.Parse(postStr);
                //通信成功
                if (res.Element("xml").Element("return_code").Value == "SUCCESS")
                {
                    if (res.Element("xml").Element("result_code").Value == "SUCCESS")
                    {
                        //交易成功
                        string ordecode = res.Element("xml").Element("out_trade_no").Value;
                        string billId = res.Element("xml").Element("transaction_id").Value;
                        string mch_id = res.Element("xml").Element("mch_id").Value;
                        string total_fee = res.Element("xml").Element("total_fee").Value;
                        var amount = decimal.Parse(total_fee) / 100;
                        //string attach = res.Element("xml").Element("attach").Value;
                        OrderManager.PayComplete(ordecode, amount, PayType.WechatPay);
                        return Content(new WXResponse
                        {
                            Code = "SUCCESS",
                            Msg = "OK"
                        }.ToString());
                    }
                    else
                    {
                        return Content(new WXResponse
                        {
                            Code = "FAIL",
                            Msg = "交易失败"
                        }.ToString());
                    }
                }
                return Content(new WXResponse
                {
                    Code = "FAIL",
                    Msg = "签名失败"
                }.ToString());
            }
            catch
            {
                return Content(new WXResponse
                {
                    Code = "FAIL",
                    Msg = "交易失败"
                }.ToString());
            }
        }

        /// <summary>
        /// 微信回调
        /// </summary>
        /// <returns></returns>
        public ActionResult WxNotify()
        {
            try
            {
                int intLen = Convert.ToInt32(HttpContext.Request.InputStream.Length);
                byte[] b = new byte[intLen];
                HttpContext.Request.InputStream.Read(b, 0, intLen);
                var postStr = System.Text.Encoding.UTF8.GetString(b);
                var res = XDocument.Parse(postStr);
                //通信成功
                if (res.Element("xml").Element("return_code").Value == "SUCCESS")
                {
                    if (res.Element("xml").Element("result_code").Value == "SUCCESS")
                    {
                        //交易成功
                        string ordecode = res.Element("xml").Element("out_trade_no").Value;
                        string billId = res.Element("xml").Element("transaction_id").Value;
                        string mch_id = res.Element("xml").Element("mch_id").Value;
                        string total_fee = res.Element("xml").Element("total_fee").Value;
                        var amount = decimal.Parse(total_fee) / 100;
                        //string attach = res.Element("xml").Element("attach").Value;
                        OrderManager.PayComplete(ordecode, amount, PayType.WechatPay);
                        return Content(new WXResponse
                        {
                            Code = "SUCCESS",
                            Msg = "OK"
                        }.ToString());
                    }
                    else
                    {
                        return Content(new WXResponse
                        {
                            Code = "FAIL",
                            Msg = "交易失败"
                        }.ToString());
                    }
                }
                return Content(new WXResponse
                {
                    Code = "FAIL",
                    Msg = "签名失败"
                }.ToString());
            }
            catch
            {
                return Content(new WXResponse
                {
                    Code = "FAIL",
                    Msg = "交易失败"
                }.ToString());
            }
        }
    }
}